import { onBeforeMount, onMounted, onUnmounted, ref } from "vue";
import { useAgvApi } from "../api/agv";
import { useIpApi } from "../api/ip";

import getVisualization from "../api/Visualization";
import Base from "../baby/Base";
import getCvInfo from "../api/CvInfo";




const useData = () => {

  const dataRef = ref<null | any>(null);
  const dataCV = ref<null | any>(null);
  const dataIP = ref<null | any[]>([]);
  const timerIdRef = ref<number | null>(null);

  const dataIpCount = ref<TIpCount>({
    disableCount: 0,
    enableCount: 0,
    onlineCount: 0,
    totalCount: 0,
    offlineCount: 0
  })


  const loadData = async () => {

    try {

      // const res = await getVisualization();
      // dataRef.value = res.data
      // console.log(res.data);
      // const cvRes = await getCvInfo()
      // dataCV.value = cvRes.data
      // console.log(cvRes.data);

      const res1 = await useIpApi().getAllIpStatus();
      // clear
      dataIpCount.value.totalCount = 0
      dataIpCount.value.enableCount = 0
      dataIpCount.value.disableCount = 0
      dataIpCount.value.onlineCount = 0
      dataIpCount.value.offlineCount = 0
      dataIP.value!.splice(0, dataIP.value!.length);
      // set value
      dataIP.value!.push(...res1.data.ipAddressArray);
      dataIpCount.value.disableCount += res1.data.disableCount;
      dataIpCount.value.enableCount += res1.data.enableCount;
      dataIpCount.value.totalCount += res1.data.totalCount;
      dataIpCount.value.onlineCount += res1.data.onlineCount;
      dataIpCount.value.offlineCount += res1.data.offlineCount;





    } catch (err) {
      console.warn(err);
    }
  };


  onMounted(() => {
    loadData();
    timerIdRef.value = setInterval(async () => await loadData(), 3000);
  });



  onUnmounted(() => {
    clearInterval(timerIdRef.value!);
  });


  return {
    dataRef,
    dataCV,
    timerIdRef,
    dataIP,
    dataIpCount
  }
}

export default useData
